from wtforms import StringField, Form
from wtforms.validators import regexp, InputRequired, ValidationError
import hashlib
from utils import redis_cach
import time


class BaseForm(Form):
    def get_error(self):
        message = self.errors.popitem()[1][0]
        return message


class SMSCaptchaForm(BaseForm):
    salt = 'nx24Tej@R4gWVCopJkjHWjBo@n58LdQ5'
    phone = StringField(validators=[regexp(r'1[23456789]\d{9}', message='请输入正确的手机号')])
    ts = StringField(validators=[regexp(r'\d{13}', message='201')])
    sign = StringField(validators=[InputRequired(message='201')])

    def validate_sign(self, field):
        sign = field.data
        phone = self.phone.data
        ts = self.ts.data
        if not sign:
            raise ValidationError(message='201')
        sms_code_60 = 'sms_code_60_{}'.format(phone)
        sms_code = redis_cach.get(sms_code_60)
        if sms_code:
            raise ValidationError(message='60秒内只能发送一条短信！')

        server_ts = round(time.time() * 1000)
        if int(server_ts) - int(ts) >= 30000:
            print('时间戳不合法', int(server_ts), int(ts), int(server_ts) - int(ts))
            return False

        sign2 = hashlib.sha256((ts+phone+self.salt).encode('utf-8')).hexdigest()
        # print('客户端提交的sign：', sign)
        # print('服务器生成的sign：', sign2)
        if sign != sign2:
            raise ValidationError(message='202')
